import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
export default function useUpdate({ rules = {}, defaultData = {} }) {
  // 添加表单
  const updateFormData = reactive<DataType>({
    ...defaultData
  });
  const updateFormRef = ref();
  const updateFormRules = reactive<DataType>(rules);

  /**
   * @description 提交表单
   * @param {*} addApi,updateApi,sendData
   * @returns
   */
  const submit = async ({
    addApi,
    updateApi,
    sendData,
    isMock = false
  }: DataType) => {

    return new Promise(async (resolve, reject) => {
      if (!updateFormRef.value) {
        reject(false);
        return;
      }
      await updateFormRef.value.validate();
      console.log("sendData",sendData)
      if (isMock) {
        setTimeout(() => {
          closeHandle();
          ElMessage({
            type: "success",
            message: "操作成功"
          });
        }, 1000);
        return;
      }
      try {
        if (rowId.value) {
          //编辑
          await updateApi(sendData);
        } else {
          //添加
          await addApi(sendData);
        }
        closeHandle();
        ElMessage({
          type: "success",
          message: "操作成功"
        });
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  };
  //打开
  const showHandle = ref(false);
  const rowId = ref();
  /**
   * @desc 打开编辑弹窗
   * @param row 行数据
   * @param id 行id
   */
  const openHandle = async ({ row, id }) => {
    console.info(row);
    resetForm();
    resetData();
    showHandle.value = true;
    rowId.value = id;
    if (updateFormRef.value) {
      setTimeout(() => {
        updateFormRef.value.clearValidate();
      }, 100);
    }
    //编辑操作
    if (id) {
      //编辑赋值
      for (const key in row) {
        if (Object.prototype.hasOwnProperty.call(row, key)) {
          updateFormData[key] = row[key];
        }
      }
    }
  };
  //重置表单
  const resetForm = () => {
    for (const key in updateFormData) {
      updateFormData[key] = undefined;
    }
  };
  //   重置数据
  const resetData = () => {
    for (const key in updateFormData) {
      updateFormData[key] = defaultData[key];
    }
  };
  //关闭弹窗
  const closeHandle = () => {
    showHandle.value = false;
    rowId.value = undefined;
    resetForm();
  };

  return {
    updateFormData,
    updateFormRef,
    updateFormRules,
    submit,
    rowId,
    showHandle,
    openHandle,
    closeHandle,
    resetData
  };
}
